<template>
  <div class="time-setting">
    <h2>设置咨询时间</h2>
    
    <!-- 已设置的时间段列表 -->
    <div class="existing-slots">
      <h3>已设置的时间段</h3>
      <el-table :data="existingTimeSlots" style="width: 100%" v-loading="loading">
        <el-table-column label="工作日" width="120">
          <template #default="{ row }">
            {{ weekdays.find(day => day.value === row.weekday)?.label }}
          </template>
        </el-table-column>
        
        <el-table-column label="时间段" width="200">
          <template #default="{ row }">
            {{ row.begTime }} - {{ row.endTime }}
          </template>
        </el-table-column>
        
        <el-table-column label="可预约人数" prop="currentCapacity" width="120" />
        
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button 
              type="danger" 
              link
              @click="handleDeleteExistingSlot(row.timelistId)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加新时间段 -->
    <div class="add-slots-section">
      <h3>添加新时间段</h3>
      <div class="time-slots">
        <div v-for="(slot, index) in timeSlots" :key="index" class="time-slot">
          <el-form :model="slot" label-width="100px">
            <el-form-item label="工作日">
              <el-select v-model="slot.weekday">
                <el-option
                  v-for="day in weekdays"
                  :key="day.value"
                  :label="day.label"
                  :value="day.value"
                />
              </el-select>
            </el-form-item>
            
            <el-form-item label="开始时间">
              <el-time-picker
                v-model="slot.begTime"
                format="HH:mm"
                placeholder="选择时间"
              />
            </el-form-item>
            
            <el-form-item label="结束时间">
              <el-time-picker
                v-model="slot.endTime"
                format="HH:mm"
                placeholder="选择时间"
              />
            </el-form-item>
            
            <el-form-item label="预约容量">
              <el-input-number
                v-model="slot.currentCapacity"
                :min="1"
                :max="10"
                :step="1"
                controls-position="right"
                placeholder="请设置可预约人数"
              />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="handleConfirmSlot(index)">确认设置</el-button>
              <el-button type="danger" @click="handleDeleteSlot(index)">删除</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <div class="actions">
        <el-button type="primary" @click="addTimeSlot">添加时间段</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  setDoctorSchedule, 
  getDoctorSchedule,
  deleteDoctorSchedule 
} from '../../api/doctor'

interface TimeSlot {
  timelistId: number
  weekday: number
  begTime: string
  endTime: string
  currentCapacity: number
  doctorId: number
}

// 工作日选项
const weekdays = [
  { label: '周一', value: 1 },
  { label: '周二', value: 2 },
  { label: '周三', value: 3 },
  { label: '周四', value: 4 },
  { label: '周五', value: 5 },
  { label: '周六', value: 6 },
  { label: '周日', value: 7 }
]

// 时间段列表
const timeSlots = ref([])
const existingTimeSlots = ref<TimeSlot[]>([])
const loading = ref(false)

// 获取已设置的时间段
const fetchTimeSlots = async () => {
  loading.value = true
  try {
    const doctorId = localStorage.getItem('doctorid')
    if (!doctorId) {
      ElMessage.error('获取用户信息失败')
      return
    }
    
    const res = await getDoctorSchedule(Number(doctorId))
    if (res.code === '200') {
      existingTimeSlots.value = res.data
    }
  } catch (error) {
    console.error('获取时间段失败:', error)
    ElMessage.error('获取时间段失败')
  } finally {
    loading.value = false
  }
}

// 添加时间段
const addTimeSlot = () => {
  timeSlots.value.push({
    weekday: '',
    begTime: '',
    endTime: '',
    currentCapacity: 1,
    doctorId: Number(localStorage.getItem('doctorid'))
  })
}

// 确认设置单个时间段
const handleConfirmSlot = async (index: number) => {
  const slot = timeSlots.value[index]
  
  // 验证数据
  if (!slot.weekday || !slot.begTime || !slot.endTime || !slot.currentCapacity) {
    ElMessage.error('请填写完整的时间段信息')
    return
  }
  
  try {
    const res = await setDoctorSchedule({
      weekday: slot.weekday,
      begTime: formatTime(slot.begTime),
      endTime: formatTime(slot.endTime),
      currentCapacity: slot.currentCapacity,
      doctorId: Number(localStorage.getItem('doctorid'))
    })
    
    if (res.code === '200') {
      ElMessage.success('时间段设置成功')
      timeSlots.value.splice(index, 1)  // 设置成功后移除该时间段
      fetchTimeSlots()  // 重新获取时间段列表
    } else {
      ElMessage.error(res.msg || '设置失败')
    }
  } catch (error: any) {
    ElMessage.error(error.message || '设置失败')
  }
}

// 删除时间段
const handleDeleteSlot = (index: number) => {
  timeSlots.value.splice(index, 1)
}

// 格式化时间
const formatTime = (time: Date) => {
  const hours = time.getHours().toString().padStart(2, '0')
  const minutes = time.getMinutes().toString().padStart(2, '0')
  return `${hours}:${minutes}`
}

// 删除已设置的时间段
const handleDeleteExistingSlot = async (timelistId: number) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个时间段吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const res = await deleteDoctorSchedule(timelistId)
    if (res.code === '200') {
      ElMessage.success('删除成功')
      fetchTimeSlots() // 重新获取时间段列表
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

onMounted(() => {
  fetchTimeSlots()
})
</script>

<style scoped>
.time-setting {
  padding: 20px;
}

h2, h3 {
  color: #2c3e50;
  margin-bottom: 20px;
}

.existing-slots {
  margin-bottom: 40px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.add-slots-section {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.time-slots {
  margin: 20px 0;
}

.time-slot {
  padding: 20px;
  margin-bottom: 20px;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
}

.actions {
  margin-top: 20px;
}

.el-form-item {
  margin-bottom: 20px;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-time-picker) {
  width: 100%;
}

h3 {
  margin: 0 0 20px;
  color: #2c3e50;
  font-size: 18px;
}
</style>